package zisu.netty.practice.netty.my;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2022/1/14 16:20
 */
public class HeartBeatReqHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private volatile ScheduledFuture<?> heartBeat;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        //ping相当于是一个死循环
        ping(ctx.channel());
    }

    private void ping(Channel channel) {
        int second = 5;
        heartBeat = channel.eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                if (channel.isActive()) {
                    System.out.println("ping");
                    //心跳包  就查看 ioserver 里面的心跳包来，看wireshake 就行
                    channel.writeAndFlush(1);
                } else {
                    System.err.println("The connection had broken, cancel the task that will send a heart beat.");
                    channel.closeFuture();
                    throw new RuntimeException();
                }
            }
        }, second, TimeUnit.SECONDS);

        heartBeat.addListener(new GenericFutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    //这里回调的作用是 让future.run()重复执行，因为channel.eventLoop().schedule()只执行一次
                    ping(channel);
                }
            }
        });
    }
}
